package com.zte.sys.login.control;


import com.zte.sys.login.model.Journal;
import com.zte.sys.login.service.UserLoginService;
import com.zte.util.OperatorLog;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
import java.util.Date;


/**
 * 操作日志切面定义
 */
@Aspect
@Controller
public class OperatorLogApsect {

    @Autowired
    private UserLoginService userLoginService;

    private static Logger logger = LogManager.getLogger(OperatorLogApsect.class);

    @Pointcut("@annotation(com.zte.util.OperatorLog)")
    public void operatorLog() {

    }

    @SuppressWarnings("rawtypes")
    @AfterReturning(pointcut="operatorLog()&&@annotation(log)")
    public void afterReturn(JoinPoint joinPoint, OperatorLog log) {

        /**
         * 接口调用信息可以记日志，也可以写到数据库
         */
        StringBuilder sb = new StringBuilder();
        sb.append("|操作:").append(log.operate());
        String jcontent = joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName();
        sb.append("--类名.方法名:").append(jcontent);
        String s = sb.toString();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpSession session = request.getSession();
        int  id =Integer.parseInt((String) session.getAttribute("id"));
        session.setAttribute("id",(String)session.getAttribute("id"));
        String module = log.module();
        int moduleId = Integer.parseInt(userLoginService.getModuleOfId(module));
        Date date = new Date();
        Journal journal = new Journal(0,moduleId,id,s,date,null,null);
        userLoginService.insertJournal(journal);
        System.out.println(journal);
        logger.info(sb.toString());
    }
}

